package cn.cvs.dao;


import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/**
 * @auth 邝志豪
 * @date 2023/8/10 9:47
 */
public class BaseDao {
    private static String driver;
    private static String url;
    private static String user;
    private static String password;

    Connection conn = null;
    static {
        into();
    }
    public static void into(){
        Properties properties = new Properties();

        String configFile = "database.properties";

        InputStream is = BaseDao.class.getClassLoader().getResourceAsStream(configFile);

        try{
            properties.load(is);
            driver = properties.getProperty("driver");
            url = properties.getProperty("url");
            user = properties.getProperty("username");
            password = properties.getProperty("password");
            Class.forName(driver);

        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public Connection getConnection(){
        try{
            if(conn == null || conn.isClosed()){
                try{
                    Class.forName(driver);
                    conn = DriverManager.getConnection(url,user,password);
                }catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }
    public void closeAll(Connection conn, Statement stmt, ResultSet rs) {
        try{
            if(rs != null){
                rs.close();
            }
            if(stmt != null){
                stmt.close();
            }
            if(conn != null){
                conn.close();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    public int exceuteUpdate(String preparedSql,Object[] param) throws SQLException {
        PreparedStatement pstmt = null;
        int num = 0;
        conn = getConnection();
        try{
            pstmt = conn.prepareStatement(preparedSql);
            if(param != null){
                for (int i = 0; i <param.length ; i++) {
                    pstmt.setObject(i+1,param[i]);
                }
            }
            num = pstmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            closeAll(conn,pstmt,null);
        }
        return num;
    }
}

